package com.yonyou.crm.common.base;

import java.io.*;
import java.lang.reflect.*;
import java.net.URLEncoder;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.yonyou.crm.common.exception.CrmMessageException;
import com.yonyou.crm.common.rest.constant.AppCodeConstant;
import com.yonyou.crm.sys.user.entity.UserVO;
import com.yonyou.crm.sys.user.rmitf.IUserRmService;

@RestController
@RequestMapping(value = "/test/excel")
public class ExcelExport {

	@Autowired
	IUserRmService userService;

	@RequestMapping(value = "export", method = RequestMethod.GET)
	public <T> Object exportExcel(HttpServletRequest request, HttpServletResponse response) throws IOException, CrmMessageException {
		Map<String, Object> param = new HashMap<>();
		List<UserVO> list = userService.getUserListExport(param);
		String[] headers = { "Id", "租户Id", "部门Id", "名称", "性别", "邮箱", "手机号", "密码", "加密盐", "职位", "类型" };
		String[] fields = { "id", "tenantId", "deptId", "name", "genderName", "email", "phone", "password", "salt", "jobName", "typeName" };
		String title = "导出测试";
		String name = "人员导出.xls";

		Map<String, Object> exportParam = new HashMap<>();
		exportParam.put("headers", headers);
		exportParam.put("fields", fields);
		exportParam.put("title", title);
		exportParam.put("name", name);

		exportDataToExcel(list, exportParam, response);
		return null;
	}

	/**
	 * @Title: exportDataToExcel
	 * @Description: 将数据导出生成excel文件
	 * @param list
	 * @param headers
	 * @param headers
	 * @param os
	 * @return Sheet
	 * @throws IOException
	 * @throws CrmMessageException
	 */
	public static <T> void exportDataToExcel(List<T> list, Map<String, Object> exportParam, HttpServletResponse response) throws CrmMessageException, IOException {
		String name = String.valueOf(exportParam.get("name"));
		// String title = String.valueOf(exportParam.get("title"));
		String[] headers = (String[]) exportParam.get("headers");
		String[] fields = (String[]) exportParam.get("fields");

		HSSFWorkbook workbook = new HSSFWorkbook();
		// 生成一个表格
		// HSSFSheet sheet = workbook.createSheet(title);
		HSSFSheet sheet = workbook.createSheet();
		// 设置表格默认列宽15个字节
		sheet.setDefaultColumnWidth(15);
		// 生成一个样式
		HSSFCellStyle style = ExcelExport.getCellStyle(workbook);
		// 生成一个字体
		HSSFFont font = ExcelExport.getFont(workbook);
		// 把字体应用到当前样式
		style.setFont(font);

		// 生成表格标题
		HSSFRow row = sheet.createRow(0);
		row.setHeight((short) 300);
		HSSFCell cell = null;

		for (int i = 0; i < headers.length; i++) {
			cell = row.createCell(i);
			cell.setCellStyle(style);
			HSSFRichTextString text = new HSSFRichTextString(headers[i]);
			cell.setCellValue(text);
		}

		// 将数据放入sheet中
		for (int i = 0; i < list.size(); i++) {
			row = sheet.createRow(i + 1);
			Object t = list.get(i);
			try {
				for (int j = 0; j < fields.length; j++) {
					cell = row.createCell(j);
					String fieldName = fields[j];
					String methodName = "get"
							+ fieldName.substring(0, 1).toUpperCase()
							+ fieldName.substring(1);
					Method getMethod = t.getClass().getMethod(methodName, new Class[] {});
					Object value = getMethod.invoke(t, new Object[] {});
					if (null == value) {
						value = "";
					}
					cell.setCellValue(value.toString());

				}
			} catch (Exception e) {
				throw new CrmMessageException(AppCodeConstant.ServerError, "获取数据错误");
			}
		}

		OutputStream os = response.getOutputStream();

		try {
			response.reset();
			response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(name, "utf-8"));
			response.setContentType("application/msexcel");
			workbook.write(os);
		} catch (Exception e) {
			throw new CrmMessageException(AppCodeConstant.ServerError, "文件导出失败");
		} finally {
			try {
				os.flush();
				os.close();
			} catch (IOException e) {
				throw new CrmMessageException(AppCodeConstant.ServerError, "输出流操作失败");
			}
		}
	}

	/**
	 * @Title: getCellStyle
	 * @Description: 获取单元格格式
	 * @param @param workbook
	 * @param @return
	 * @return HSSFCellStyle
	 * @throws
	 */
	public static HSSFCellStyle getCellStyle(HSSFWorkbook workbook) {
		HSSFCellStyle style = workbook.createCellStyle();
		style.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
		style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		style.setBorderTop(HSSFCellStyle.BORDER_THIN);
		style.setLeftBorderColor(HSSFCellStyle.BORDER_THIN);
		style.setRightBorderColor(HSSFCellStyle.BORDER_THIN);
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);

		return style;
	}

	/**
	 * @Title: getFont
	 * @Description: 生成字体样式
	 * @param @param workbook
	 * @param @return
	 * @return HSSFFont
	 * @throws
	 */
	public static HSSFFont getFont(HSSFWorkbook workbook) {
		HSSFFont font = workbook.createFont();
		font.setColor(HSSFColor.WHITE.index);
		font.setFontHeightInPoints((short) 12);
		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		return font;
	}

}
